package com.ea.admin.service.impl;

import com.ea.admin.pojo.po.RedisCode;
import com.ea.admin.service.VerifyService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class VerifyServiceImpl implements VerifyService {
    @Resource
    RedisTemplate<String, Object> redisTemplate;
    public static final String VERIFY_PHONE_KEY_PREFIX = "VERIFY_PHONE_USER_ID";

    @Override
    public RedisCode getExistCode( String emailOrPhone) {
        Object redisGet = redisTemplate.opsForHash().get(VERIFY_PHONE_KEY_PREFIX, emailOrPhone);
        RedisCode redisCode = null;
        if(redisGet != null) {
            redisCode = (RedisCode) redisGet;
        }
        return redisCode;
    }

    @Override
    public void refreshCode(Integer code, String emailOrPhone) {
        RedisCode redisCode = new RedisCode(code, new Date());
        redisTemplate.opsForHash().put(VERIFY_PHONE_KEY_PREFIX, emailOrPhone, redisCode);
    }

    @Override
    public void saveCode(Integer code, String emailOrPhone) {
        RedisCode redisCode = new RedisCode(code, new Date());
        redisTemplate.opsForHash().put(VERIFY_PHONE_KEY_PREFIX, emailOrPhone, redisCode);
    }

    @Override
    public int checkCode(Integer code, String emailOrPhone) {
        RedisCode existCode = getExistCode(emailOrPhone);
        if(existCode != null && existCode.getCode().equals(code)){
            //判断是否超时
            //1 验证码正确 0 验证码错误 -1 验证码超时
            if(existCode.getTime().getTime() - new Date().getTime() > 60 * -1000){
                //全部正常，删除redis中的验证码。
                deleteCode(code, emailOrPhone);
                return 1;
            }
            else {
                deleteCode(code, emailOrPhone);
                return -1;
            }
        }
        return 0;
    }

    private void deleteCode(Integer code, String emailOrPhone) {
        redisTemplate.opsForHash().delete(VERIFY_PHONE_KEY_PREFIX, emailOrPhone);
    }
}
